package com.king.headline.UI;


import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.king.headline.R;
import com.king.headline.adapter.AdapterDialogSelectTxt;
import com.king.headline.base.BaseActivity;
import com.king.headline.beans.UserInfo;
import com.king.headline.net.Callback;
import com.king.headline.net.NetWork;
import com.king.headline.util.AccountManager;
import com.king.headline.util.Configuration;
import com.king.headline.util.CustomToast;
import com.king.headline.util.DialogUtils;
import com.king.headline.util.UIUtils;
import com.king.headline.util.UploadPicManager;
import com.king.headline.util.Utils;
import com.king.headline.view.CircleImageView;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 设置界面
 *
 * @author Administrator
 */
public class SettingActivity extends BaseActivity implements OnClickListener {
    @BindView(R.id.bt_loging)
    AppCompatButton bt_loging;
    @BindView(R.id.iv_chatHeadurl)
    CircleImageView iv_chatHeadurl;
    @BindView(R.id.tv_nickName)
    TextView tv_nickName;
    @BindView(R.id.tv_logout)
    TextView tv_logout;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.iv_left2)
    ImageView iv_left2;
    @BindView(R.id.tv_title2)
    TextView tv_title2;
    @BindView(R.id.rl_setPsw)
    RelativeLayout rl_setPsw;
    @BindView(R.id.rl_nickName)
    RelativeLayout rl_nickName;

    @BindView(R.id.tv_weichat_bind)
    TextView tv_weichat_bind;
    @BindView(R.id.tv_qq_bind)
    TextView tv_qq_bind;
    @BindView(R.id.tv_weibo_bind)
    TextView tv_weibo_bind;

    @BindView(R.id.rl_weichat_bind)
    RelativeLayout rl_weichat_bind;
    @BindView(R.id.rl_qq_bind)
    RelativeLayout rl_qq_bind;
    @BindView(R.id.rl_weibo_bind)
    RelativeLayout rl_weibo_bind;
    @BindView(R.id.rl_phone)
    RelativeLayout rl_phone;

    @BindView(R.id.rl_changePic)
    RelativeLayout rl_changePic;
    @BindView(R.id.tv_name_modify)
    TextView tv_name_modify;
    private Bitmap mBitmap;
    private ProgressDialog mwaitingDialog;
    private static final String IMAGE_FILE_NAME = "temp.jpg";
    private UserInfo userInfo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UIUtils.addActivity(this);
        baseSetContentView(R.layout.activity_setting);
        initView();
        setTopBarAndAction();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AccountManager.getInstance().getUser()==null){
            finish();
        }
    }
    private void setUserInfo() {
        userInfo = AccountManager.getInstance().getUser();
        if (userInfo != null) {

            if (TextUtils.isEmpty(userInfo.nickname)){
                tv_nickName.setText("可修改昵称");
            }else{
                tv_nickName.setText(userInfo.nickname);
            }
            UIUtils.getImageLoader().displayImage(Configuration.API_HOST + userInfo.chatHeadurl, iv_chatHeadurl);

            if (userInfo.isSetPassWord){
                //设置过密码到，跳转修改密码节目
                tv_name_modify.setText("可修改密码");
            }else{
                //如果没有设置过密码，跳转设置密码界面
                tv_name_modify.setText("可设置密码");
            }

            if (TextUtils.isEmpty(userInfo.telephone)){
                tv_phone.setText("未绑定");
                tv_phone.setTextColor(UIUtils.getColor(R.color.myred));
            }else{
                tv_phone.setText(userInfo.getPhoneNumber());
                tv_phone.setTextColor(UIUtils.getColor(R.color.text_gray));
            }
            if (TextUtils.isEmpty(userInfo.qqJson)){
                tv_qq_bind.setText("未绑定");
                tv_qq_bind.setTextColor(UIUtils.getColor(R.color.myred));
            }else{
                tv_qq_bind.setText("已绑定");
                tv_qq_bind.setTextColor(UIUtils.getColor(R.color.text_gray));
            }
            if (TextUtils.isEmpty(userInfo.wechatJson)){
                tv_weichat_bind.setText("未绑定");
                tv_weichat_bind.setTextColor(UIUtils.getColor(R.color.myred));
            }else{
                tv_weichat_bind.setText("已绑定");
                tv_weichat_bind.setTextColor(UIUtils.getColor(R.color.text_gray));
            }
            if (TextUtils.isEmpty(userInfo.weiboJson)){
                tv_weibo_bind.setText("未绑定");
                tv_weibo_bind.setTextColor(UIUtils.getColor(R.color.myred));
            }else{
                tv_weibo_bind.setText("已绑定");
                tv_weibo_bind.setTextColor(UIUtils.getColor(R.color.text_gray));
            }
        } else {
            AccountManager.goLogingActivity();
        }
    }
    private void initView() {
        tv_title2.setText("个人资料");
        tv_logout.setOnClickListener(this);
        iv_left2.setOnClickListener(this);
        rl_changePic.setOnClickListener(this);
        rl_setPsw.setOnClickListener(this);
        rl_nickName.setOnClickListener(this);
        rl_weichat_bind.setOnClickListener(this);
        rl_weibo_bind.setOnClickListener(this);
        rl_qq_bind.setOnClickListener(this);
        rl_phone.setOnClickListener(this);
        setUserInfo();
    }

    private void setTopBarAndAction() {
        setBarTitleText(""); // 去掉默认标题栏，使用自定义的
        setBackIcon(true);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        UIUtils.removeActivity(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_logout:
                DialogUtils.showHintDialogTwo(this, "确定退出登录?", new DialogUtils.OnDialogListener() {
                    @Override
                    public void onOk(View v) {
                        SettingActivity.this.finish();
                        AccountManager.getInstance().logout();
                    }

                    @Override
                    public void onCancel(View v) {

                    }
                });

                break;
            case R.id.iv_left2:
                finish();
                break;
            case R.id.rl_changePic:
                showDialog();
                break;
            case R.id.rl_nickName:
                DialogUtils.showModifyNickNameDialog(this,tv_nickName.getText().toString(), new DialogUtils.OnDialogListener() {
                    @Override
                    public void onOk(View v) {
                        String text = v.getTag().toString();
                        NetWork.getInstance().modifyNickName(userInfo.encyptdId, userInfo.apikey, text, new Callback() {
                            @Override
                            public void success(String result) {
                                login();
                                CustomToast.showToast("修改成功");
                            }

                            @Override
                            public void notice(JSONObject jsonObject, String message) {
                                CustomToast.showToast(message);
                            }

                            @Override
                            public void failed(String e) {
                                CustomToast.showToast(e);
                            }
                        });
                    }

                    @Override
                    public void onCancel(View v) {

                    }
                });
                break;
            case R.id.rl_setPsw:
                if (TextUtils.isEmpty(userInfo.telephone)){
                    DialogUtils.showHintDialogOne(this,"系统检测到您尚未绑定手机号,请先绑定手机号码");
                    break;
                }
                if (userInfo.isSetPassWord){
                    //设置过密码到，跳转修改密码节目
                    tv_name_modify.setText("可修改密码");
                    Intent intent1 = new Intent(this,ModifyPswActivity.class);
                    startActivity(intent1);
                }else{
                    //如果没有设置过密码，跳转设置密码界面
                    tv_name_modify.setText("可设置密码");
                    Intent intent = new Intent(this,GetPswActivity.class);
                    intent.putExtra("actStr", "set");
                    startActivity(intent);
                }
                break;
            case R.id.rl_weichat_bind:
                CustomToast.showToast("该功能暂未开放");
                break;
            case R.id.rl_weibo_bind:
                CustomToast.showToast("该功能暂未开放");
                break;
            case R.id.rl_qq_bind:
//                if (tv_qq_bind.getText().equals("已绑定")){
//
//                    LoginRemoveBind(SHARE_MEDIA.QQ);
//                }else {
////                    loginThreeUtils.setManageType(2);
////                    loginThreeUtils.loginThree(SHARE_MEDIA.QQ);
//                }

                break;
            case R.id.rl_phone:
                Intent intent;
                if (userInfo!=null && TextUtils.isEmpty(userInfo.telephone)){
                    intent = new Intent(this,BindPhoneActivity.class);
                }else{
                    intent = new Intent(this,BindModifyPhoneActivity.class);
                }
                startActivity(intent);
                break;
        }

    }
//    private void LoginRemoveBind(final SHARE_MEDIA shareMedia){
//        DialogUtils.showHintDialogTwo(this, "确定要解除账号与" + shareMedia + "的绑定?", new DialogUtils.OnDialogListener() {
//            @Override
//            public void onOk(View v) {
////                loginThreeUtils.LoginRemoveBind3ToNet(shareMedia);
//            }
//
//            @Override
//            public void onCancel(View v) {
//
//            }
//        });
//    }

    /**
     * 显示选择对话框
     */
    private void showDialog() {
        List<AdapterDialogSelectTxt.Item> items = new ArrayList<AdapterDialogSelectTxt.Item>();
        AdapterDialogSelectTxt.Item item0 = new AdapterDialogSelectTxt.Item();
        item0.name = "拍照上传";
        item0.object = 0;
        AdapterDialogSelectTxt.Item item1 = new AdapterDialogSelectTxt.Item();
        item1.name = "选择本地照片";
        item1.object = 1;
        items.add(item0);
        items.add(item1);
        DialogUtils.showSelectDialog(this, "更换头像", items, new DialogUtils.OnItemSelectListener() {
            @Override
            public void onItemSelected(AdapterDialogSelectTxt.Item item) {
                int which = (int) item.object;
                switch (which) {
                    case 1:
                        Intent intentFromGallery = new Intent();
                        intentFromGallery.setType("image/*"); // 设置文件类型
                        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intentFromGallery, 1);
                        break;
                    case 0:
                        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        // 判断存储卡是否可以用，可用进行存储
                        String state = Environment.getExternalStorageState();
                        if (state.equals(Environment.MEDIA_MOUNTED)) {
                            // 照了照片后就保存在这里(照完相片后直接保存在faceImage.jpg中)
                            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
                        }
                        startActivityForResult(intentFromCapture, 2);
                        break;
                }
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 如果是直接从相册获取
            case 1:
                if(data != null)
                    UploadPicManager.getInstance(this).startPhotoZoom(data.getData());
                break;
            // 如果是调用相机拍照时
            case 2:
                File temp = new File(Environment.getExternalStorageDirectory()+ "/temp.jpg");
                if(temp != null && temp.exists())
                    UploadPicManager.getInstance(this).startPhotoZoom(Uri.fromFile(temp));
                break;
            // 取得裁剪后的图片
            case 3:
                if(data != null){
                   setPicToView(data);
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);

    }



    /**
     * 保存裁剪之后的图片数据，并且上传到网上
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            mBitmap = extras.getParcelable("data");
            try {
                FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory()+ "/faceImage.jpg");
                mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                String picPath=Environment.getExternalStorageDirectory()+"/faceImage.jpg";
                mwaitingDialog = ProgressDialog.show(this,"头像上传中", "请稍候...");
                UserInfo userInfo = AccountManager.getInstance().getUser();
                NetWork.getInstance().setNickPic(userInfo.encyptdId, userInfo.apikey, picPath, new Callback() {
                    @Override
                    public void success(String result) {
                        Utils.dismissProgressDialog(mwaitingDialog);

                        login();
                    }

                    @Override
                    public void notice(JSONObject jsonObject, String message) {
                        Utils.dismissProgressDialog(mwaitingDialog);
                        CustomToast.showToast(message);
                    }

                    @Override
                    public void failed(String e) {
                        Utils.dismissProgressDialog(mwaitingDialog);
                        CustomToast.showToast(e);
                    }
                });

            } catch (FileNotFoundException e) {
                Utils.dismissProgressDialog(mwaitingDialog);
                e.printStackTrace();
            }


        }
    }

    public void login() {
        NetWork.getInstance().login(AccountManager.getInstance().getUser().apikey, new Callback() {
            @Override
            public void success(String result) {
                Utils.dismissProgressDialog(mwaitingDialog);
                UserInfo userInfo = new Gson().fromJson(result, UserInfo.class);
                AccountManager.getInstance().setUser(userInfo);
                initView();
            }

            @Override
            public void notice(JSONObject jsonObject, String message) {
                Utils.dismissProgressDialog(mwaitingDialog);
            }

            @Override
            public void failed(String e) {
                Utils.dismissProgressDialog(mwaitingDialog);
            }
        });
    }

}
